package com.nb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nb.domain.Category;
import com.nb.result.Result;
import com.nb.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //分页器
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name){
        //分页构造器
        Page pageInfo = new Page(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> lqw= new LambdaQueryWrapper<>();
        //过滤条件 当name不为空时
        lqw.like(StringUtils.isNotEmpty(name),Category::getName,name);
        //排序条件
        lqw.orderByDesc(Category::getUpdateTime);
        //查询
        categoryService.page(pageInfo,lqw);
        return Result.success(pageInfo);
    }

    //保存
    @PostMapping
    public Result<String> saveCategory(@RequestBody Category category){
        boolean save = categoryService.save(category);
        if (!save) {
            return Result.error("保存失败!");
        }
        return Result.success("保存成功！");
    }

    @DeleteMapping
    public Result<String> deleteById(Long id){
        categoryService.removeById(id);
        return Result.success("删除成功！");
    }

    @PutMapping
    public Result<String> updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return Result.success("修改成功！");
    }

    //查询菜品的分类信息
    @GetMapping("/list")
    public Result<List<Category>> get(Category category){
        //查询器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //查询条件
        lqw.eq(category.getType() != null,Category::getType,category.getType());
        //排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //查询并返回结果
        List<Category> list = categoryService.list(lqw);
        return Result.success(list);
    }


}
